package io.gitee.sfch.chunmi.springframework;

import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

/**
 * Jackson格式化全局配置
 */
@Configuration
public class JacksonConf {

    private static final DateTimeFormatter NORM_DATE_FORMATTER = DateTimeFormatter
            .ofPattern("yyyy-MM-dd", Locale.getDefault())
            .withZone(ZoneId.systemDefault());
    private static final DateTimeFormatter NORM_DATETIME_FORMATTER = DateTimeFormatter
            .ofPattern("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
            .withZone(ZoneId.systemDefault());

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
        return builder -> {
            // 时间格式化
            builder.simpleDateFormat("yyyy-MM-dd HH:mm:ss");
            builder.serializers(new LocalDateSerializer(NORM_DATE_FORMATTER));
            builder.serializers(new LocalDateTimeSerializer(NORM_DATETIME_FORMATTER));

            // Long格式化
            builder.serializerByType(Long.class, new ToStringSerializer());
            builder.serializerByType(long.class, new ToStringSerializer());
        };
    }
}
